// (C)
// 2009
// Dang
// Kien
// Thanh
﻿if (document.title == "Binh trường: Xác nhận xuất binh")
{
    var a = document.getElementsByTagName("script");
    var g_urlRoot = "";
    for (var i = 0; i < a.length; i++)
    {
        if (a[i].src.indexOf("dequoc.js") !=- 1) {
            g_urlRoot = a[i].src.substring(0, a[i].src.indexOf("dequoc.js"));
            break;
        }
    }
    var aScripts = ['md5.js', 'canvas.js'];
    for (var i = 0; i < aScripts.length; i++)
    {
        var script = document.createElement('script');
        script.src = g_urlRoot + aScripts[i];
        document.getElementsByTagName('head')[0].appendChild(script);
    }
}
var g_bQuick = true;
var heso = 
{
    "nguy" : [[40, 30, 70, 0, 0], [0, 0, 0, 120, 180]], "thuc" : [[15, 65, 0, 0, 0], [0, 0, 90, 45, 140]], 
    "ngo" : [[40, 10, 60, 0, 0], [0, 0, 0, 55, 150]]
};
var g_sXuatChinh = "";
var g_campDef = [[], [], []];
var g_generalAtk = 0;
var g_generalAtkPercent = 0;
var g_aTroopSkill = [1, 1, 1, 1, 1, 1, 1];
var g_aTroopValue = ["", "", "", "", "", "", ""];
var g_aTroopMax = [0, 0, 0, 0, 0, 0, 0];
var g_aTroop = [0, 0, 0, 0, 0, 0, 0];
var g_checkInfo = {
    target : false, campDef : false, blacksmith : false
};
var g_multiplier = 8.5;
var g_nTargetX = 0;
var g_nTargetY = 0;
var g_troopType = "";
var g_aGeneral = [];
var g_campLevel = 0;
var g_campName = "";
var g_campNum = 0;
function isNgoaiThanh()
{
    return!!($("cityOuter"));
}
function isTrongThanh()
{
    return!!($("cityInner"));
}
function isRightPanel()
{
    return!!($("right"));
}
function isLeftPanel()
{
    return!!($("left"));
}
function isQuanPhuBaoKho()
{
    return document.title.include("Quan phủ: Bảo khố");
}
function isTinTucChienDau()
{
    return document.title.include("Tin tức chiến đấu");
}
function isHopThuDen()
{
    return document.title.include("Hộp thư đến");
}
function isXacNhanXuatBinh()
{
    return document.title.include("Binh trường: Xác nhận xuất binh");
}
function isChienBao()
{
    return document.title.include("Binh trường: Tin tức");
}
function isBinhTruong()
{
    return document.title.include("Binh trường: Xuất binh");
}
function isMucTieuLichSu()
{
    return document.title.include("历史目标");
}
function isBanDoKhuVuc()
{
    return document.title.include("BĐ K.vực");
}
function isBXHLM()
{
    return document.title.include("Bảng xếp hạng liên minh");
}
function isLMYL()
{
    return document.title.include("Liên minh yếu lược");
}
function isDSTV()
{
    return document.title.include("Thành viên");
}
function isTTHC()
{
    return document.title.include("Tin tức vận chuyển");
}
Event.observe(window, "load", function ()
{
    if (isNgoaiThanh()) {}
    if (isTrongThanh()) {}
    if (isRightPanel())
    {
        calCampDefByLevel();
        createControlPanel();
        getTroopInfo();
        window.setInterval(getTroopInfo, 60000);
    }
    if (isLeftPanel()) {}
    if (!!($("menuOuter_vn_VN"))) {}
    if (isQuanPhuBaoKho()) {
        createBaoKhoPatch();
    }
    if (isDSTV())
    {
        var div = new Element("div", {
            style : "margin-bottom: -1em"
        });
        div.innerHTML = '<a href="javascript:getDanhSachThanhVien();">getDanhSachThanhVien()</a>';
        $("resBar").parentNode.insert(div);
    }
    if (isBXHLM())
    {
        var div = new Element("div", {
            style : "margin-bottom: -1em"
        });
        div.innerHTML = '<a href="javascript:getDanhSachLienMinh();">getDanhSachLienMinh()</a>';
        $("resBar").parentNode.insert(div);
    }
    if (isTinTucChienDau())
    {
        document.body.select("table.table td")[0].insert('&nbsp;<a href="javascript:void(0)" onclick="checkSonTrai(\'sơn trại\');">Sơn trại</a>')
    }
    if (isHopThuDen())
    {
        document.body.select("table.table")[1].select("td")[0].insert('&nbsp;<a href="javascript:void(0)" onclick="checkBaoVat(\'Tin báo : Bảo vật đã\');">Bảo vật</a>');
    }
    if (isBanDoKhuVuc())
    {
        var div = new Element("div", {
            style : "margin-bottom: -1em"
        });
        div.innerHTML = ['<a href="javascript:showPlain();" title="Hiện số ruộng lúa của đất trống">Địa hình</a>', 
        '&nbsp;<a href="javascript:showCommandCenter();" title="Tìm kiếm mục tiêu quanh vùng">Mục tiêu</a>', 
        '&nbsp;<input type="checkbox" id="chkQuick" checked title="Khi nhấn vào sơn trại thì chuyển luôn sang trang Xuất binh" onchange="g_bQuick=!g_bQuick;">Chọn nhanh', 
        '&nbsp;<a href="javascript:showAutoFarmPanel();" title="Hiện bảng điều khiển auto farm cho tất cả các thành">Auto farm</a>'].join("");
        $("resBar").parentNode.insert({
            bottom : div
        });
        showLevel();
        Wicket.replaceOuterHtml = function (element, text)
        {
            var range = element.ownerDocument.createRange();
            range.selectNode(element);
            var fragment = range.createContextualFragment(text);
            element.parentNode.replaceChild(fragment, element);
            showLevel();
        }
    }
    if (isMucTieuLichSu())
    {
        var div = new Element("div", {
            style : "margin-bottom: -1em"
        });
        div.innerHTML = ['<a href="javascript:checkCamp();">checkCamp()</a> '].join("");
        $("resBar").parentNode.insert(div);
        checkCamp();
    }
    if (isBinhTruong() && $("actionForm_troopList_0_troopType")) {
        createBinhTruongPatch();
    }
    if (isXacNhanXuatBinh())
    {
        var a = document.body.select("img");
        if (a.length > 0)
        {
            document.body.select("input[name='captchacon:ccaptcha']")[0].value = getString(a[0], true);
        }
        if (top.frames.length > 0)
        {
            g_bAutoFarm = top.frames[4].g_bAutoFarm;
            if (g_bAutoFarm)
            {
                document.body.select("form")[0].submit();
                setTimeout(function ()
                {
                    top.frames[4].markCamp.call(top.frames[4], top.frames[3].g_campName);
                    top.frames[4].getTroopInfo.call(top.frames[4]);
                    if (top.frames[3].g_aGeneral.length > 1)
                    {
                        top.frames[4].farmNextTarget.call(top.frames[4], top.frames[3].g_aTroopMax, top.frames[3].g_aGeneral[1]);
                    }
                }, 500);
            }
        }
    }
});
function createBinhTruongPatch()
{
    calCampDefByLevel();
    var troopCSS = $("actionForm_troopList_0_troopType").className;
    var imageNo = troopCSS.substring(troopCSS.indexOf("_") + 1);
    g_troopType = imageNo <= 7 ? "nguy" : imageNo <= 14 ? "ngo" : "thuc";
    document.body.select("h4")[0].insert('&nbsp;<span>Hệ số an toàn <input type="text" value="' + g_multiplier + '" size="3" id="txtMultiplier"></span>') calLevelTuong();
    if (g_aGeneral.length <= 0) {
        return;
    }
    if (top.frames.length > 0) {
        g_bAutoFarm = top.frames[4].g_bAutoFarm;
    }
    if (g_bAutoFarm)
    {
        g_checkInfo = top.frames[4].g_checkInfo;
        document.body.select("input[name='posX']")[0].value = top.frames[4].g_nTargetX;
        document.body.select("input[name='posY']")[0].value = top.frames[4].g_nTargetY;
        g_campLevel = top.frames[4].g_campLevel;
        g_campNum = g_campDef[2][Math.round(g_campLevel / 5) - 1];
        g_campName = top.frames[4].g_campName;
        if (!$("divMucTieuMessage"))
        {
            document.body.select("h4")[0].insert("<span id='divMucTieuMessage' style='color:red; font-weight:bold'>... đang lấy thông tin mục tiêu...</span>")
        }
        $("divMucTieuMessage").innerHTML = ["Sơn trại cấp ", g_campLevel, ", ", g_campNum, " quân"].join("");
        g_checkInfo.campDef = true;
        $("actionType_1").checked = true;
        if (g_checkInfo.blacksmith) {
            g_aTroopSkill = top.frames[4].g_aTroopSkill;
        }
    }
    if (!g_checkInfo.blacksmith) {
        calPhanTramLoRen();
    }
    else {
        showPhanTramLoRen();
    }
    if (!g_checkInfo.campDef) {
        calLevelSonTrai();
    }
    if (g_bAutoFarm)
    {
        document.body.select("input[name=radioGroup][value='" + g_aGeneral[0].radio + "']")[0].checked = true;
        g_generalAtk = g_aGeneral[0].attack;
        g_generalAtkPercent = g_aGeneral[0].atkPercent;
        if (calLinhCanThiet())
        {
            for (var i = 0; i < g_aTroop.length; i++) {
                if (g_aTroopValue[i] != "") {
                    g_aTroopMax[i] -= $(g_aTroopValue[i]).value;
                }
            }
            var btn = document.body.select("button")[0];
            btn.onclick.apply(btn);
        }
        else
        {
            top.frames[4].farmNextTarget.call(top.frames[4], g_aTroopMax, g_aGeneral.length > 0 ? g_aGeneral[0] : null);
        }
    }
}
function calLinhCanThiet()
{
    var bOK = false;
    for (var i = 0; i < g_aTroopPriority[g_troopType].length; i++)
    {
        if (g_aTroopValue[g_aTroopPriority[g_troopType][i]] == "") {
            continue;
        }
        if (autoCal(g_aTroopPriority[g_troopType][i])) {
            bOK = true;
            break;
        }
    }
    return bOK;
}
function calLevelTuong()
{
    var table = document.body.select("table.table")[1];
    var aAttack = table.select("td span[class='icon att']");
    var aName = table.select("td b");
    var aWeapon = table.select("td[class='kuan p0'] span") var aStar = table.select("td span[title='军衔']");
    var aWeaponLevel = ["Sơ luyện", "Nhị luyện", "Tam luyện", "Tứ luyện", "Ngũ luyện", "Lục luyện", "Thất luyện", 
    "Bát luyện", "Cửu luyện", "Thập luyện"];
    var aRadio = document.body.select("input[name=radioGroup]");
    for (var i = 0; i < aName.length; i++)
    {
        var nAtk = aAttack[i].innerHTML;
        var nAtkPercent = parseInt(aStar[i].innerHTML);
        for (var j = 0; j < 10; j++) {
            if (aWeapon[i * 3].title.include(aWeaponLevel[j])) {
                nAtkPercent += 10 * (j + 1);
                break;
            }
        }
        g_aGeneral.push(
        {
            name : aName[i].innerHTML.escapeHTML(), attack : nAtk, atkPercent : nAtkPercent, radio : aRadio[i].value
        });
    }
    g_aGeneral.sort(function (a, b)
    {
        if (b.atkPercent != a.atkPercent) {
            return b.atkPercent - a.atkPercent;
        }
        return b.attack - a.attack;
    });
    g_aGeneral.each(function (g)
    {
        document.body.select("input[name=radioGroup][value='" + g.radio + "']")[0].observe("change", function ()
        {
            g_generalAtk = g.attack;
            g_generalAtkPercent = g.atkPercent;
        });
    });
}
function calCampDefByLevel()
{
    var npc = [[10, 0, 0, 0, 0, 0, 0, 0, 0, 0], [9, 9, 0, 0, 0, 0, 0, 0, 0, 0], [15, 18, 0, 0, 0, 0, 0, 
    0, 0, 0], [33, 30, 0, 0, 0, 0, 0, 0, 0, 0], [33, 20, 47, 0, 0, 0, 0, 0, 0, 0], [60, 66, 52, 0, 0, 
    0, 0, 0, 0, 0], [72, 100, 111, 0, 0, 0, 0, 0, 0, 0], [58, 74, 88, 120, 0, 0, 0, 0, 0, 0], [70, 140, 
    95, 200, 0, 0, 0, 0, 0, 0], [110, 180, 150, 300, 0, 0, 0, 0, 0, 0], [155, 198, 172, 240, 234, 0, 0, 
    0, 0, 0], [200, 200, 240, 400, 311, 0, 0, 0, 0, 0], [100, 350, 250, 330, 352, 301, 0, 0, 0, 0], [400, 
    490, 395, 350, 400, 420, 0, 0, 0, 0], [378, 500, 333, 420, 458, 342, 289, 0, 0, 0], [330, 450, 400, 
    200, 430, 800, 500, 0, 0, 0], [500, 120, 800, 250, 700, 350, 110, 315, 0, 0], [366, 477, 288, 354, 
    178, 421, 361, 505, 0, 0], [999, 123, 455, 411, 296, 188, 398, 521, 423, 0], [100, 88, 66, 777, 666, 
    111, 222, 333, 121, 551]];
    var npcDef = [[25, 35, 40, 66, 70, 80, 140, 380, 170, 440], [10, 40, 60, 50, 33, 70, 200, 240, 250, 
    520]];
    for (var i = 0; i < 20; i++)
    {
        g_campDef[0][i] = g_campDef[1][i] = g_campDef[2][i] = 0;
        for (j = 0; j < 10; j++)
        {
            g_campDef[0][i] += npc[i][j] * npcDef[0][j];
            g_campDef[1][i] += npc[i][j] * npcDef[1][j];
            g_campDef[2][i] += npc[i][j];
        }
    }
}
function calLevelSonTrai()
{
    calCampDefByLevel();
    var x = document.body.select("input[name='posX']")[0].value;
    var y = document.body.select("input[name='posY']")[0].value;
    document.body.select("h4")[0].insert("<span id='divMucTieuMessage' style='color:red; font-weight:bold'>... đang lấy thông tin mục tiêu...</span>") var sURL = location.href.split("do/")[0];
    new Ajax.Request([sURL, "do/fbm/map/MapSmall/y/", y, "/x/", x, "/"].join(""), 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var s1 = ["(", x, ",", y, ")"].join("");
            var s2 = 'da="';
            var s3 = '" title="'var idx1 = s.indexOf(s1);
            s = s.substring(idx1 > 200 ? idx1 - 200 : 0, idx1) idx1 = s.lastIndexOf(s2);
            a = s.substring(idx1 + s2.length, s.indexOf(s3, idx1)).split("`");
            g_campLevel = a[4];
            g_campNum = a[5];
            g_checkInfo.campDef = true;
            $("divMucTieuMessage").style.color = "black";
            if (a[6] != "--")
            {
                $("divMucTieuMessage").innerHTML = ["Thành cấp ", g_campLevel, ", ", g_campNum, " dân"].join("");
            }
            else if (a[4] != "--")
            {
                $("divMucTieuMessage").innerHTML = ["Sơn trại cấp ", g_campLevel, ", ", g_campNum, " quân"].join("");
            }
            else {
                $("divMucTieuMessage").innerHTML = "Đất hoang";
            }
        }
    });
}
function calPhanTramLoRen()
{
    var innerId = document.body.select("a.ch")[0].href.split("c/")[1].split("/")[0];
    var url = location.href.split("do/")[0];
    document.body.select("h4")[0].insert("<span id='divLoRenMessage' style='color:red; font-weight:bold'>... đang lấy thông tin lò rèn...</span>") new Ajax.Request(url + "do/fbm/inner/id/" + innerId, 

    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var idx1 = s.indexOf('title="Lò rèn`');
            if (idx1 ==- 1)
            {
                g_checkInfo.blacksmith = true;
                $("divLoRenMessage").innerHTML = "";
                showPhanTramLoRen();
                return;
            }
            var idx2 = s.indexOf('?x=', idx1);
            idx1 = s.indexOf('"></a>', idx2);
            new Ajax.Request(s.substring(idx1, idx2), 
            {
                method : "get",
                onSuccess : function (response)
                {
                    var s = response.responseText;
                    var idx1 =- 1;
                    var idx2 =- 1;
                    var s1 = 'class="icond troop_';
                    var s2 = 'class="icon att_a">';
                    var s3 = '%';
                    var a = [];
                    for (var i = 0; i < 7; i++)
                    {
                        idx1 = s.indexOf('id="troopIcon' + i);
                        if (idx1 ==- 1) {
                            break;
                        }
                        idx2 = s.indexOf(s1, idx1);
                        var troopType = (parseInt(s.substr(idx2 + s1.length, 2)) - 1) % 7;
                        idx1 = s.indexOf(s2, idx2);
                        var atkPercent = parseInt(s.substr(idx1 + s2.length, 2));
                        g_aTroopSkill[troopType] = atkPercent;
                    }
                },
                onFaluire : function (response)
                {
                    JLog.write(JColor.YELLOW_RED, "Lò rèn");
                },
                onComplete : function ()
                {
                    g_checkInfo.blacksmith = true;
                    $("divLoRenMessage").innerHTML = "";
                    showPhanTramLoRen();
                }
            });
        },
        onFaluire : function (response)
        {
            JLog.write(JColor.YELLOW_RED, "Trong thành");
        }
    });
}
function showPhanTramLoRen()
{
    var a = document.body.select("table.table")[0].select("td");
    for (var i = 4; i < a.length; i += 4)
    {
        var troopType = (a[i].select("span")[0].className.split("_")[1] - 1) % 7;
        g_aTroopMax[troopType] = parseInt(a[i + 2].innerHTML);
        g_aTroopValue[troopType] = a[i + 3].select("input")[0].id;
        a[i + 1].insert(['<div class="icon att_a" title="% Tấn công">', '<input size="3" width="30px" value="', 
        g_aTroopSkill[troopType], '" id="txt_', g_aTroopValue[troopType], '" onchange="g_aTroopSkill[', 
        troopType, ']=parseInt(this.value);">', '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="$(\'txt_', 
        g_aTroopValue[troopType], '\').value=32;g_aTroopSkill[', troopType, ']=32;">32%</a>', '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="$(\'txt_', 
        g_aTroopValue[troopType], '\').value=30;g_aTroopSkill[', troopType, ']=30;">30%</a>', '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="$(\'txt_', 
        g_aTroopValue[troopType], '\').value=1;g_aTroopSkill[', troopType, ']=1;">1%</a>', '</div>'].join(""));
        a[i + 2].insert(['&nbsp;<a href="javascript:void(0)" onclick="cal(', troopType, ');">Tính</a>', 
        '&nbsp;<a href="javascript:void(0)" onclick="xoa(', troopType, ');">Xóa</a>'].join(""));
    }
}
function xoa(no)
{
    if (g_aTroopValue[no] != "") {
        $(g_aTroopValue[no]).value = 0;
    }
}
function autoCal(troopNo)
{
    var data = 
    {
        troopType : g_troopType, multiplier : $("txtMultiplier").value, aTroop : [], aTroopSkill : g_aTroopSkill, 
        heroAttack : 0, heroSkill : 0, groundDef : 0, horseDef : 0
    }
    for (var i = 0; i < 5; i++) {
        data.aTroop[i] = (g_aTroopValue[i] != "" ? $(g_aTroopValue[i]).value || 0 : 0);
    }
    data.heroAttack = g_generalAtk;
    data.heroSkill = g_generalAtkPercent;
    data.groundDef = g_campDef[0][Math.round(g_campLevel / 5) - 1];
    data.horseDef = g_campDef[1][Math.round(g_campLevel / 5) - 1];
    var min = 0;
    var max = 0;
    var count = 0;
    data.aTroop[troopNo] = max;
    while (count < 100) {
        data.aTroop[troopNo] = max;
        if (checkNum(data)) {
            break;
        }
        max += 10000;
        count++;
    }
    count = 0;
    var num = 0;
    var isOK = false;
    while (count < 100)
    {
        data.aTroop[troopNo] = max;
        isOK = checkNum(data);
        if (isOK) {
            num = max;
            max = Math.round((min + num) / 2);
        }
        else {
            min = max;
            max = Math.round((min + num) / 2);
        }
        if (max == min || max == num) {
            break;
        }
        count++;
    }
    var troopMin = g_aTroopMin[g_troopType][troopNo];
    if (max <= g_aTroopMax[troopNo])
    {
        if (g_aTroopMax[troopNo] <= troopMin) {
            max = g_aTroopMax[troopNo];
        }
        else {
            max = Math.max(max, troopMin);
        }
        $(g_aTroopValue[troopNo]).value = max;
        return true;
    }
    else {
        $(g_aTroopValue[troopNo]).value = g_aTroopMax[troopNo];
        return false;
    }
}
function cal(troopNo)
{
    var data = 
    {
        troopType : g_troopType, multiplier : $("txtMultiplier").value, aTroop : [], aTroopSkill : g_aTroopSkill, 
        heroAttack : 0, heroSkill : 0, groundDef : 0, horseDef : 0
    }
    for (var i = 0; i < 5; i++) {
        data.aTroop[i] = (g_aTroopValue[i] != "" ? $(g_aTroopValue[i]).value || 0 : 0);
    }
    data.heroAttack = g_generalAtk;
    data.heroSkill = g_generalAtkPercent;
    data.groundDef = g_campDef[0][Math.round(g_campLevel / 5) - 1];
    data.horseDef = g_campDef[1][Math.round(g_campLevel / 5) - 1];
    var min = 0;
    var max = 0;
    var count = 0;
    data.aTroop[troopNo] = max;
    while (count < 100) {
        data.aTroop[troopNo] = max;
        if (checkNum(data)) {
            break;
        }
        max += 10000;
        count++;
    }
    count = 0;
    var num = 0;
    var isOK = false;
    while (count < 100)
    {
        data.aTroop[troopNo] = max;
        isOK = checkNum(data);
        if (isOK) {
            num = max;
            max = Math.round((min + num) / 2);
        }
        else {
            min = max;
            max = Math.round((min + num) / 2);
        }
        if (max == min || max == num) {
            break;
        }
        count++;
    }
    $(g_aTroopValue[troopNo]).value = max;
}
function checkNum(o)
{
    var groundAtk = 0, horseAtk = 0, totalAtk = 0, totaldefense = 0, neededDamage = 0;
    for (var i = 0; i < 5; i++)
    {
        groundAtk += o.aTroop[i] * heso[o.troopType][0][i] * (o.aTroopSkill[i] / 100 + 1);
        horseAtk += o.aTroop[i] * heso[o.troopType][1][i] * (o.aTroopSkill[i] / 100 + 1);
    }
    groundAtk = Math.round((groundAtk + o.heroAttack / 2) * (o.heroSkill / 100 + 1));
    horseAtk = Math.round((horseAtk + o.heroAttack / 2) * (o.heroSkill / 100 + 1));
    totalDamage = groundAtk + horseAtk;
    totalDefense = Math.round((o.groundDef * groundAtk + o.horseDef * horseAtk) / totalDamage);
    neededDamage = Math.round(totalDefense * o.multiplier);
    return totalDamage > neededDamage;
}
function createControlPanel()
{
    var div = new Element("div", {
        id : "divControlPanel"
    });
    div.innerHTML = ["<a id='area_0_toggle' href='javascript:toggleMessageWin();'>Expand</a> ", "<a href='javascript:getTroopInfo()' title='Xem số lượng quân trong thành'>Quân</a> ", 
    "<a href='javascript:autoFarm()' title='Bật, tắt Auto Farm'>Auto</a>: <span id='divAutoFarm'>Off</span> ", 
    "<a href='javascript:farmNextTarget()' title='Không chờ timer, cho quân đi farm ngay lập tức'>Farm</a>"].join("");
    $("right").insert(div);
}
function toggleMessageWin()
{
    if ($("area_0").offsetHeight < 100) {
        $("area_0").style.height = "250px";
        $("area_0_toggle").innerHTML = "Collapse";
    }
    else {
        $("area_0").style.height = "70px";
        $("area_0_toggle").innerHTML = "Expand";
    }
}
function getDanhSachLienMinh()
{
    var cnt = 0;
    var aDanhSach = [];
    var aRow = $("center").select("table.table")[0].select("tr");
    for (var i = 1; i < aRow.length - 1; i++)
    {
        aRow[i].select("a").each(function (a)
        {
            if (a.innerHTML == "Xem") {
                return;
            }
            var lienminh = a.innerHTML.stripTags();
            var url = a.href;
            JLog.write(++cnt, lienminh, url);
            aDanhSach.push({
                lienminh : lienminh, url : url
            });
        });
    }
    JLog.write("==========================================");
    aDanhSach.each(function (o)
    {
        ajax2DanhSachThanhVienLink(o.lienminh, o.url);
    })
}
function getDanhSachThanhVien()
{
    var cnt = 0;
    var aDanhSach = [];
    $("center").select("table.table")[0].select("a").each(function (a)
    {
        var member = a.innerHTML.stripTags();
        var url = a.href;
        aDanhSach.push({
            member : member, url : url
        });
    });
    JLog.write("==========================================");
    aDanhSach.each(function (o)
    {
        getThanhVienInfo(o.member, o.url, "---");
    })
}
function ajax2DanhSachThanhVienLink(lienminh, url)
{
    var rootURL = location.href;
    var idx = rootURL.indexOf("?");
    var rootURL = idx < 0 ? rootURL : rootURL.substring(0, idx);
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var s1 = 'a class="ch" href="';
            var s2 = '"><span>Thành viên</span></a>';
            var idx1 = s.indexOf(s1);
            idx1 = s.indexOf(s1, idx1 + 1);
            var idx2 = s.indexOf(s2, idx1);
            var sMemberListURL = rootURL + s.substring(idx1 + s1.length, idx2);
            ajax2DanhSachThanhVien(lienminh, sMemberListURL);
        },
        onFaluire : function (response)
        {
            JLog.write(JColor.YELLOW_RED, lienminh);
        }
    });
}
function ajax2DanhSachThanhVien(lienminh, url)
{
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var s1 = 'table cellspacing="0" class="table"';
            var s2 = 'a href="';
            var s3 = '"><span>';
            var s4 = '</span></a></td>';
            var idx1 = s.indexOf(s1);
            var idx2 = s.indexOf(s2, idx1);
            var idx3 =- 1;
            var idx4 =- 1;
            var memberURL = "";
            var member = "";
            while (idx2 > 0)
            {
                idx3 = s.indexOf(s3, idx2);
                memberURL = s.substring(idx2 + s2.length, idx3);
                idx4 = s.indexOf(s4, idx3);
                member = s.substring(idx3 + s3.length, idx4);
                getThanhVienInfo(member, memberURL, lienminh);
                idx1 = idx2 + 1;
                idx2 = s.indexOf(s2, idx1);
            }
        },
        onFaluire : function (response)
        {
            JLog.write(JColor.YELLOW_RED, "ajax2DanhSachThanhVien", lienminh);
        }
    });
}
function getThanhVienInfo(member, url, lienminh)
{
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var s1 = 'Tội lỗi:';
            var s2 = '</span>';
            var idx1 = s.indexOf(s1);
            var idx2 = s.indexOf(s2, idx1);
            var nToiloi = s.substring(idx1 + s1.length, idx2).stripTags() if (nToiloi >= 100)
            {
                var s3 = '<table class="table">';
                var s4 = '<span id="infoBody_cityCt_citiesList_';
                var s5 = '</td>';
                var s6 = '<td><span>';
                idx1 = s.indexOf(s4, idx2);
                while (idx1 !=- 1)
                {
                    idx2 = s.indexOf(s5, idx1);
                    var sTenThanh = s.substring(idx1, idx2).stripTags();
                    idx1 = s.indexOf(s6, idx2);
                    idx2 = s.indexOf(s5, idx1);
                    var sChau = s.substring(idx2, idx1).stripTags();
                    idx1 = s.indexOf(s6, idx2);
                    idx2 = s.indexOf(s5, idx1);
                    var sToaDo = s.substring(idx2, idx1).stripTags();
                    idx1 = s.indexOf(s6, idx2);
                    idx2 = s.indexOf(s5, idx1);
                    var sDanSo = s.substring(idx2, idx1).stripTags();
                    JLog.write(lienminh, member, nToiloi, sTenThanh, sChau, sToaDo, sDanSo);
                    idx1 = s.indexOf(s4, idx2);
                }
            }
            else if (nToiloi >= 50) {}
        },
        onFaluire : function (response)
        {
            JLog.write(JColor.YELLOW_RED, member);
        }
    });
}
function showLevel()
{
    var aId = [];
    $("tile").select("a").each(function (a)
    {
        var cityDataStr = a.getAttribute("da");
        if (cityDataStr == "") {
            cityDataStr = "`````````";
        }
        var cityData = cityDataStr.split("`");
        if (cityData[4] != "--")
        {
            a.parentNode.innerHTML += ["<div style='float:left; margin-left:-48px; font-weight:bold; ", 
            cityData[5] == 0 ? "color:darkgray;" : "color:red;", "'>", cityData[4], "</div>"].join("");
            if (cityData[6] == "--") {
                aId.push(a.id);
            }
        }
    });
    while (aId.length > 0)
    {
        a = $(aId.pop());
        if (a.getAttribute("quick") == "1") {
            continue;
        }
        a.setAttribute("quick", "1");
        a.observe("click", function (e)
        {
            if (!g_bQuick) {
                return;
            }
            Event.stop(e);
            new Ajax.Request(this.href, 
            {
                method : "get",
                onSuccess : function (response)
                {
                    var s = response.responseText;
                    var s1 = 'Xem vị trí trên BĐ Tam Quốc';
                    var s2 = 'a href="';
                    var idx1 = s.indexOf(s1);
                    var idx2 = s.indexOf(s2, idx1 + s1.length) + s2.length;
                    idx1 = s.indexOf('"', idx2);
                    location.href = s.substring(idx2, idx1);
                }
            });
        });
    }
}
function showPlain()
{
    var aPlain = [];
    $("tile").select("a").each(function (a)
    {
        var cityDataStr = a.getAttribute("da");
        if (cityDataStr == "") {
            cityDataStr = "`````````";
        }
        var cityData = cityDataStr.split("`");
        if (cityData[4] == "--") {
            aPlain.push(a.id);
        }
    });
    aPlain.each(function (id)
    {
        new Ajax.Request($(id).href, 
        {
            method : "get",
            onSuccess : function (response)
            {
                var s = response.responseText;
                var s1 = '<span class="icond plain_1">';
                var s2 = '</span>';
                var idx1 = s.indexOf(s1);
                var idx2 = s.indexOf(s2, idx1);
                var nType = [14, "<span style='background-color:pink; font-weight:bold;'>12</span>", 10, 
                8, 6][s.substring(idx1 + s1.length, idx2)];
                $(id).parentNode.innerHTML += ["<div style='float:left; margin-left:-48px; color:green; background-color:yellow;'>", 
                nType, "</div>"].join("");
            },
            onFaluire : function (response)
            {
                JLog.write(JColor.YELLOW_RED, id);
            }
        });
    });
}
function checkCamp()
{
    var a = $("body").select("table.table a");
    for (var i = 0; i < a.length; i++)
    {
        if (!a[i].text.include("Sơn trại")) {
            continue;
        }
        ajaxCheckCamp(a[i - 1].href, function (link)
        {
            link.setStyle({
                color : "red"
            });
        }
        .bind(null, a[i + 1]), function (link)
        {
            link.setStyle({
                color : "lightgray", fontWeight : "normal"
            });
        }
        .bind(null, a[i + 1]));
    }
}
function ajaxCheckCamp(url, fnOK, fnFaluire)
{
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            if (response.responseText.include('Du dân') && fnOK) {
                fnOK();
            }
            else if (fnFaluire) {
                fnFaluire();
            }
        },
        onFaluire : function (response)
        {
            if (fnFaluire) {
                fnFaluire();
            }
        }
    });
}
function ajaxGetMinDamage(url, fnOK, fnFaluire)
{
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            var aGroundDef = [25, 35, 40, 66, 70, 80, 140, 380, 170, 440];
            var aHorseDef = [10, 40, 60, 50, 33, 70, 200, 240, 250, 520];
            var idx1 = 0, idx2 = 0, idx3 = 0;
            var s1 = "", s2 = "</span>", s3 = "";
            for (var i = 0; i < 10; i++)
            {
                var s1 = "icon bandits_" + (i + 1);
                idx1 = s.indexOf(s1);
                if (idx1 ==- 1) {
                    continue;
                }
                idx2 = s.indexOf(s2, idx1);
                var s3 = s.substring(idx1 + s1.length, idx2);
                a[i] = s3.substring(s3.lastIndexOf(" ") + 1);
            }
            var num = 0;
            JLog.write(a);
        },
        onFaluire : function (response)
        {
            if (fnFaluire) {
                fnFaluire();
            }
        }
    });
}
function getTroopInfo()
{
    var url = $$("div.quick_c")[0].select("a")[0].href;
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            if (!$("divQuanXuatChinh"))
            {
                var div = new Element("div", {
                    id : "divQuanXuatChinh", style : "margin-bottom: 10px;"
                });
                $("divControlPanel").appendChild(div);
            }
            if (!$("divQuanTrongThanh"))
            {
                var div = new Element("div", {
                    id : "divQuanTrongThanh"
                });
                $("divControlPanel").appendChild(div);
            }
            var s1 = '<h4>Quân trong thành:</h4>';
            var s2 = '<span class="troop">';
            var s3 = '</td>';
            var idx1 = s.indexOf(s1);
            var idx2 = s.indexOf(s2, idx1);
            if (idx2 ==- 1)
            {
                $("divQuanTrongThanh").innerHTML = "<b>Quân trong thành:</b><br>Không có quân trong thành";
            }
            else
            {
                var idx1 = s.indexOf(s3, idx2);
                $("divQuanTrongThanh").innerHTML = ["<b>Quân trong thành:</b><br>", s.substring(idx2, 
                idx1)].join("");
            }
            s1 = "Quân xuất chinh:";
            s2 = "Bổn thành tấn công"s3 = "quân tấn công";
            idx1 = s.indexOf(s1);
            idx2 = s.indexOf(s2, idx1);
            var a = [];
            g_sXuatChinh = "";
            while (idx2 !=- 1)
            {
                idx1 = s.indexOf(s3, idx2);
                if (idx1 ==- 1) {
                    break;
                }
                a.push(s.substring(idx2 + s2.length, idx1).stripTags().strip());
                idx2 = s.indexOf(s2, idx1);
            }
            g_sXuatChinh = a.join("`");
            $("divQuanXuatChinh").innerHTML = ["<b>Quân xuất chinh:</b><br>" + a.join("<br>")].join("");
        },
        onFaluire : function (response)
        {
            JLog.write("getTroopInfo().onFailure");
        }
    });
}
function showAutoFarmPanel()
{
    JLog.write("showAutoFarmPanel");
}
function showCommandCenter()
{
    if (!$("divCommandCenter"))
    {
        var div = new Element("div", 
        {
            id : "divCommandCenter", style : "width:100%; margin-top: 30px; display:none; border: 1px dotted #999999;"
        });
        $("center").insert(div, {
            position : "bottom"
        });
        var info = $("mapList_24_tileLink").getAttribute("da").split("`");
        var sSelect = ['<select id="selectLevel" size="1" onchange="filterLevel()">', '<option value="All" selected="selected">All</option>'];
        for (var i = 1; i <= 20; i++) {
            sSelect.push('<option value="', i * 5, '">', i * 5, '</option>')
        }
        sSelect.push('</select>');
        div.innerHTML = ['<table class="table">', ' <tr>', '  <td>Tâm ', '   X:<input id="divXCenter" type="textbox" maxlength="3" value="', 
        parseInt(info[2]), '" style="width:25px;">&nbsp; ', '   Y:<input id="divYCenter" type="textbox" maxlength="3" value="', 
        parseInt(info[3]), '" style="width:25px;">', '   Phạm vi: <input id="divSize" type="textbox" maxlength="1" value="5" style="width:10px;">', 
        '  </td>', '  <td>', '   <div style="float: left;">', '    <a href="javascript:scanMap()">Tìm kiếm</a>&nbsp;', 
        '    Lọc: ', sSelect.join(""), '    <span id="divMessage"></span>', '   </div>', '   <div style="float: right;">', 
        '    <a href="javascript:void(0);" onclick="$(\'divText\').toggle();">Backup</a>', '   </div>', 
        '  </td>', ' </tr>', ' <tr valign=top>', '  <td>', '   <a href="javascript:void(0)" onclick="javascript:$(\'divCamp\').toggle();">Sơn trại</a><br>', 
        '   <a href="javascript:void(0)" onclick="javascript:$(\'divCity\').toggle();">Mỏ farm</a><br>', 
        '   <a href="javascript:void(0)" onclick="javascript:$(\'divBookmark\').toggle();">Auto farm</a><br>', 
        '   <div id="divSubMap" style="position:relative; width:175px; height:175px;">', '   </div>', 
        '  </td>', '  <td>', '   <div id="divText" style="max-height: 200px; display:none; margin-bottom:20px;">', 
        '<textarea id="txtDump"></textarea>', '<a href="javascript:void(0)" onclick="javascript:dumpData();">Save</a> ', 
        '<a href="javascript:void(0)" onclick="javascript:loadData();">Load<a> ', '<a href="javascript:void(0)" onclick="javascript:$(\'divText\').toggle();">Close</a>', 
        '</div>', '   <div id="divCamp" style="overflow-y: auto; max-height: 200px;"></div><br>', '   <div id="divCity" style="overflow-y: auto; max-height: 200px;"></div>', 
        '   <div id="divBookmark" style="overflow-y: auto; max-height: 200px;">', '<textarea id="textBookmark"></textarea>', 
        '<a href="javascript:void(0)" onclick="javascript:loadAutoData();">Auto<a> ', '<a href="javascript:void(0)" onclick="javascript:clearAutoData();">Clear<a> ', 
        '</div>', '  </td>', ' </tr>', '</table>'].join("");
    }
    $("divCommandCenter").toggle();
}
function clearAutoData()
{
    $("textBookmark").value = "";
    g_aBookmark.clear();
}
function loadAutoData()
{
    if (top.frames.length < 4) {
        return;
    }
    if (top.frames[4].g_bAutoFarm) {
        top.frames[4].autoFarm.call(top.frames[4]);
    }
    var aTarget = top.frames[4].g_aTargetList;
    aTarget.clear();
    var a = eval("[" + $("textBookmark").value + "]");
    for (var i = 0; i < a.length; i++)
    {
        var s = a[i].split("`");
        aTarget.push({
            x : s[2], y : s[3], level : s[4], name : s[1].strip(), isRed : false, lastCounter :- 1
        });
    }
    top.frames[4].autoFarm.call(top.frames[4]);
}
function loadData()
{
    var o = eval("[" + $("txtDump").value + "]")[0];
    g_x = o.x;
    g_y = o.y;
    g_size = o.size;
    g_aCamp = [];
    g_aCity = [];
    g_nCounter = 0;
    o.camp.each(function (e)
    {
        g_aCamp.push(e.split("`"));
    });
    o.city.each(function (e)
    {
        g_aCity.push(e.split("`"));
    });
    createSubMap(g_x, g_y, g_size);
    showScanResult(g_x, g_y, g_size);
    $("divMessage").innerHTML = "";
    g_bScanning = false;
    $('divText').style.display = "none";
}
function dumpBookmark()
{
    var sBookmark = [];
    for (var i = 0; i < g_aBookmark.length; i++) {
        sBookmark.push(g_aBookmark[i].join("`").replace(/\"/, '""'));
    }
    $("textBookmark").value = '"' + sBookmark.join('",\n"') + '"';
}
function dumpData()
{
    var sCamp = [];
    for (var i = 0; i < g_aCamp.length; i++) {
        sCamp.push(g_aCamp[i].join("`").replace(/\"/, '""'));
    }
    var sCity = [];
    for (var i = 0; i < g_aCity.length; i++) {
        sCity.push(g_aCity[i].join("`").replace(/\"/, '""'));
    }
    var s = ['{', 'x:', g_x, ',', 'y:', g_y, ',', 'size:', g_size, ',', 'camp:["', sCamp.join('","'), 
    '"],', 'city:["', sCity.join('","'), '"]', '}'].join("");
    $("txtDump").value = s;
}
var g_aCamp = [];
var g_aCity = [];
var g_aBookmark = [];
var g_x = 0;
var g_y = 9;
var g_size = 0;
var g_bScanning = false;
var g_nCounter = 0;
function scanMap(xCenter, yCenter, scanDistance)
{
    if (g_bScanning) {
        JLog.write("Error... Scanning...");
        return;
    }
    g_bScanning = true;
    var x = xCenter || 500;
    var y = yCenter || 500;
    var size = scanDistance || 5;
    if (arguments.length == 0)
    {
        x = parseInt($("divXCenter").value) || 500;
        y = parseInt($("divYCenter").value) || 500;
        size = parseInt($("divSize").value) || 1;
    }
    g_x = x;
    g_y = y;
    g_size = size;
    g_aCamp = [];
    g_aCity = [];
    $("divCamp").innerHTML = "";
    $("divCity").innerHTML = "";
    g_nCounter = size * size;
    $("divMessage").innerHTML = ["Xử lý... <font color='red'>", g_nCounter, "</font>"].join("");
    var sURL = location.href.split("do/")[0];
    for (var i = 0; i < size; i++)
    {
        for (var j = 0; j < size; j++)
        {
            new Ajax.Request([sURL, "do/fbm/map/MapSmall/y/", y + 7 * Math.floor(i - (size - size % 2) / 2), 
            "/x/", x + 7 * Math.floor(j - (size - size % 2) / 2), "/"].join(""), 
            {
                method : "get",
                onSuccess : function (response)
                {
                    if (g_nCounter <= 0) {
                        return;
                    }
                    var s = response.responseText;
                    var s1 = 'da="';
                    var s2 = '" title="';
                    var idx1 = 0;
                    var idx2 = 0;
                    idx1 = s.indexOf(s1, idx2);
                    while (idx1 !=- 1)
                    {
                        idx2 = s.indexOf(s2, idx1);
                        if (idx2 ==- 1) {
                            JLog.write(s.escapeHTML());
                            break;
                        }
                        var o = s.substring(idx1 + s1.length, idx2).split('`');
                        if (o[4] != "--") {
                            if (o[6] == "--") {
                                g_aCamp.push(o);
                            }
                            else {
                                o[1] = o[1].escapeHTML();
                                g_aCity.push(o);
                            }
                        }
                        idx1 = s.indexOf(s1, idx2);
                    }
                },
                onComplete : function (response)
                {
                    if (g_nCounter <= 0) {
                        return;
                    }
                    g_nCounter--;
                    $("divMessage").innerHTML = ["Xử lý... <font color='red'>", g_nCounter, "</font>"].join("");
                    if (g_nCounter <= 0)
                    {
                        $("divMessage").innerHTML = "Sắp xếp...";
                        createSubMap(x, y, size);
                        showScanResult(x, y, size);
                        $("divMessage").innerHTML = "";
                        g_bScanning = false;
                    }
                }
            });
        }
    }
}
function createSubMap(x, y, size)
{
    var o = $("divSubMap");
    o.innerHTML = "";
    var w = o.getWidth();
    var h = o.getHeight();
    for (var i = 0; i < size; i++)
    {
        for (var j = 0; j < size; j++)
        {
            var div = new Element("div", 
            {
                id : "div" + i + "_" + j, style : [i == 0 ? "border-left: 1px solid #B5B673;" : "", j == 0 ? "border-top: 1px solid #B5B673;" : "", 
                "border-bottom: 1px solid #B5B673;", "border-right: 1px solid #B5B673;", "position: absolute;", 
                "top:", Math.round(j * w / size), "px;", "left:", Math.round(i * h / size), "px;", "width:", 
                Math.round(w / size), "px;", "height:", Math.round(h / size), "px;"].join("")
            }) o.insert(div);
        }
    }
}
function filterLevel()
{
    var val = $("selectLevel").value;
    if (val == "All")
    {
        for (var i = 1; i <= 20; i++) {
            $$("tr.camp" + (i * 5)).each(function (tr)
            {
                tr.style.display = "";
            });
        }
    }
    else
    {
        for (var i = 1; i <= 20; i++)
        {
            if ((i * 5) == val) {
                $$("tr.camp" + (i * 5)).each(function (tr)
                {
                    tr.style.display = "";
                });
            }
            else {
                $$("tr.camp" + (i * 5)).each(function (tr)
                {
                    tr.style.display = "none";
                });
            }
        }
    }
}
function sortDistanceLevel(a, b)
{
    if (a[10] != b[10]) {
        return a[10] - b[10];
    }
    return b[4] - a[4];
}
function sortLevelDistance(a, b)
{
    if (a[4] != b[4]) {
        return b[4] - a[4];
    }
    return a[10] - b[10];
}
function showScanResult(x, y, size)
{
    var aCamp = ["<table id='tableCamp' class='table'><tr><td>Mục tiêu</td><td>Tọa độ</td><td>Cấp độ</td><td>Action</td></tr>"];
    var aCity = ["<table id='tableCity' class='table'><tr><td>Mục tiêu</td><td>Tọa độ</td><td>Số dân</td><td>Action</td></tr>"];
    for (var i = 0; i < g_aCamp.length; i++)
    {
        g_aCamp[i][10] = (g_aCamp[i][2] - x) * (g_aCamp[i][2] - x) + (g_aCamp[i][3] - y) * (g_aCamp[i][3] - y);
    }
    for (var i = 0; i < g_aCity.length; i++)
    {
        g_aCity[i][10] = (g_aCity[i][2] - x) * (g_aCity[i][2] - x) + (g_aCity[i][3] - y) * (g_aCity[i][3] - y);
    }
    g_aCamp.sort(sortLevelDistance);
    g_aCity.sort(sortLevelDistance);
    var url = location.href.split("do/")[0];
    for (var i = 0; i < g_aCamp.length; i++)
    {
        var info = g_aCamp[i];
        aCamp.push(["<tr class='camp", info[4], "' onmouseover='targetListOver(this, \"camp\",", x, ",", 
        y, ",", size, ",", info[2], ",", info[3], ")' onmouseout='targetListOut(this, \"camp\",", x, ",", 
        y, ",", size, ",", info[2], ",", info[3], ")' >", "<td>", info[1], "</td>", "<td>(", info[2], 
        ", ", info[3], ")</td>", "<td align='right'>", info[4], "</td>", "<td>", "<a id='mark", info[2], 
        "_", info[3], "' href='javascript:void(0);' onclick='add2Bookmark(", i, ")'>Mark</a> ", "<a id='link", 
        info[2], "_", info[3], "' target='_blank' href='", url + "do/fbm/map/MapSmall/y/", info[3], "/x/", 
        info[2], "/'>Xuất binh </a> ", "<a href='javascript:void(0);' onclick='checkLink(\"", url + "do/fbm/map/MapSmall/y/", 
        info[3], "/x/", info[2], "/\",", info[2], ",", info[3], ");'>Check</a> ", "</td>", "<tr>"].join(""));
    }
    for (var i = 0; i < g_aCity.length; i++)
    {
        var info = g_aCity[i];
        aCity.push(["<tr class='city", info[4], "' title='", info[9] == 0 ? "Thành phụ" : "Thủ đô", "-", 
        info[6], "-Chủ thành:", info[8], "-Liên minh", info[7], "' onmouseover='targetListOver(this, \"city\",", 
        x, ",", y, ",", size, ",", info[2], ",", info[3], ")' onmouseout='targetListOut(this, \"city\",", 
        x, ",", y, ",", size, ",", info[2], ",", info[3], ")' >", "<td>", info[1], "</td>", "<td>(", info[2], 
        ", ", info[3], ")</td>", "<td align='right'>", info[5], "</td>", "<td><a target='_blank' href='", 
        url + "do/fbm/map/MapSmall/y/", info[3], "/x/", info[2], "/'>Xuất binh</a></td>", "<tr>"].join(""));
    }
    aCamp.push("</table>") aCity.push("</table>")$("divCamp").innerHTML = aCamp.join("");
    $("divCity").innerHTML = aCity.join("");
}
function add2Bookmark(num)
{
    g_aBookmark.push(g_aCamp[num]);
    dumpBookmark();
}
function checkLink(url, x, y)
{
    $("link" + x + "_" + y).style.color = "#00BC00";
    new Ajax.Request(url, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var s1 = ["(", x, ",", y, ")"].join("");
            var s2 = 'da="';
            var s3 = '" title="'var idx1 = s.indexOf(s1);
            s = s.substring(idx1 > 200 ? idx1 - 200 : 0, idx1) idx1 = s.lastIndexOf(s2);
            $("link" + x + "_" + y).style.color = s.substring(idx1 + s2.length, s.indexOf(s3, idx1)).split("`")[5] == 0 ? "lightgray" : "red";
        }
    });
}
function targetListOver(tr, type, x0, y0, size, x, y)
{
    tr.style.backgroundColor = type == "camp" ? "yellow" : "cyan";
    var o = $("divSubMap");
    var w = o.getWidth();
    var h = o.getHeight();
    var i = Math.floor((x - x0 + 3) / 7) + Math.floor(size / 2);
    var j = Math.floor((y - y0 + 3) / 7) + Math.floor(size / 2);
    if ($("div" + i + "_" + j)) {
        $("div" + i + "_" + j).style.backgroundColor = type == "camp" ? "yellow" : "cyan";
    }
}
function targetListOut(tr, type, x0, y0, size, x, y)
{
    tr.style.backgroundColor = "transparent";
    var o = $("divSubMap");
    var w = o.getWidth();
    var h = o.getHeight();
    var i = Math.floor((x - x0 + 3) / 7) + Math.floor(size / 2);
    var j = Math.floor((y - y0 + 3) / 7) + Math.floor(size / 2);
    if ($("div" + i + "_" + j)) {
        $("div" + i + "_" + j).style.backgroundColor = "transparent";
    }
}
function checkSonTrai(s)
{
    var a = document.body.select("table.table td");
    for (var i = 3; i < a.length; i += 3)
    {
        if (a[i].innerHTML.include(s))
        {
            a[i + 2].select("input[type='checkbox']")[0].checked = a[i + 2].select("input[type='checkbox']")[0].checked == false ? true : false;
        }
    }
}
function checkBaoVat(s)
{
    var a = document.body.select("table.table")[1].select("td");
    for (var i = 4; i < a.length; i += 4)
    {
        if (a[i].innerHTML.include(s))
        {
            a[i + 3].select("input[type='checkbox']")[0].checked = a[i + 3].select("input[type='checkbox']")[0].checked == false ? true : false;
        }
    }
}
function setNgoaiThanhData(data) {}
function sendItems()
{
    var a = document.body.select("table.table")[1].select("td");
    var nCounter = 0;
    var url = location.href.split("do/")[0];
    for (var i = 4; i < a.length; i += 3)
    {
        var box = a[i].select('input[type="checkbox"]')[0];
        if (box.checked == false) {
            continue;
        }
        var s = a[i + 1].innerHTML;
        if (!s.include("Hiến tặng")) {
            continue;
        }
        var aLinks = s.split("<a");
        s = aLinks[aLinks.length - 1];
        var s1 = "wicketAjaxGet('";
        var idx1 = s.indexOf(s1);
        var idx2 = s.indexOf("'", idx1 + s1.length);
        s = s.substring(idx1 + s1.length, idx2);
        nCounter++;
        new Ajax.Request(url + "do/" + s, 
        {
            method : "get",
            onSuccess : function (response)
            {
                var s = response.responseText;
                var s1 = 'settings.src="';
                var idx1 = s.indexOf(s1);
                var idx2 = s.indexOf('"', idx1 + s1.length);
                var urlForm = s.substring(idx1 + s1.length, idx2);
                new Ajax.Request(url + "do/" + urlForm, 
                {
                    method : "get",
                    onSuccess : function (response)
                    {
                        var s = response.responseText;
                        var s1 = 'action="';
                        var idx1 = s.indexOf(s1);
                        var idx2 = s.indexOf('"', idx1 + s1.length);
                        new Ajax.Request(url + "do/" + s.substring(idx1 + s1.length, idx2), 
                        {
                            method : "post", parameters : 
                            {
                                iF_hf_0 : "", txtCityName : "", txtPosx : $("sendPosX").value, txtPosy : $("sendPosY").value, 
                                txtMsg : "", item : ""
                            },
                            onSuccess : function (response) {},
                            onComplete : function ()
                            {
                                nCounter--;
                                if (nCounter == 0) {
                                    location.href = location.href;
                                }
                            }
                        });
                    }
                });
            }
        });
    }
}
function createBaoKhoPatch()
{
    document.body.select("h4")[0].insert(['&nbsp;X: <input type="text" size=3 width="30px" id="sendPosX">', 
    '&nbsp;Y: <input type="text" size=3 width="30px" id="sendPosY">', '&nbsp;<a href="javascript:void(0);" onclick="sendItems()">Gửi đồng loạt</a>'].join(""));
    var a = document.body.select("table.table")[1].select("td");
    for (var i = 4; i < a.length; i += 3) {
        a[i].insert({
            top : '<input type="checkbox">'
        });
    }
}
var g_bAutoFarm = false;
var g_aTargetList = [];
var g_aTroopPriority = {
    "nguy" : [4, 3, 2, 0, 1], "thuc" : [4, 2, 1, 0, 3], "ngo" : [4, 2, 0, 3, 1], 
};
var g_aTroopMin = {
    "nguy" : [100, 100, 100, 10, 10], "thuc" : [100, 100, 10, 10, 10], "ngo" : [100, 100, 100, 10, 10], 
};
var g_nTargetId =- 1;
var g_intervalAutoFarm = null;
var g_intervalAutoScan = null;
function autoFarm()
{
    g_bAutoFarm = !g_bAutoFarm;
    $("divAutoFarm").innerHTML = g_bAutoFarm ? "<font color='red'><b>On</b></font>" : "Off";
    if (!g_bAutoFarm)
    {
        if (g_intervalAutoFarm != null) {
            window.clearInterval(g_intervalAutoFarm);
        }
        if (g_intervalAutoScan != null) {
            window.clearInterval(g_intervalAutoScan);
        }
        return;
    }
    auto_LoRen();
    if (g_intervalAutoFarm != null) {
        window.clearInterval(g_intervalAutoFarm);
    }
    g_intervalAutoFarm = window.setInterval(function ()
    {
        JLog.write("farmNextTarget<br>interval");
        farmNextTarget();
    }, 30000);
    if (g_intervalAutoScan != null) {
        window.clearInterval(g_intervalAutoScan);
    }
    g_intervalAutoScan = window.setInterval(function ()
    {
        JLog.write("scanTarget<br>interval");
        scanTarget();
    }, 1800000);
}
var g_nScanCounter = 0;
function scanTarget()
{
    if (!g_bAutoFarm) {
        return;
    }
    g_nScanCounter++;
    JLog.write(JColor.YELLOW_BLUE, "... scanning...");
    for (var i = 0; i < g_aTargetList.length; i++)
    {
        if (g_sXuatChinh.include(g_aTargetList[i].name)) {
            g_aTargetList[i].isRed = false;
            g_aTargetList[i].lastCounter = g_nScanCounter;
        }
    }
    for (var i = 0; i < g_aTargetList.length; i += 10) {
        scanNextTarget(i);
    }
}
function scanNextTarget(targetId)
{
    if (targetId >= g_aTargetList.length) {
        JLog.write("... scanning... done.");
        return;
    }
    while (g_aTargetList[targetId].lastCounter >= g_nScanCounter)
    {
        targetId++;
        if (targetId >= g_aTargetList.length) {
            JLog.write("... scanning... done.");
            return;
        }
    }
    var sURL = location.href.split("do/")[0];
    var x = g_aTargetList[targetId].x;
    var y = g_aTargetList[targetId].y;
    new Ajax.Request([sURL, "do/fbm/map/MapSmall/y/", y, "/x/", x, "/"].join(""), 
    {
        method : "get",
        onSuccess : function (response)
        {
            if (g_aTargetList[targetId].lastCounter >= g_nScanCounter) {
                return;
            }
            checkXY(response.responseText, x, y);
        },
        onComplete : function ()
        {
            setTimeout(function ()
            {
                scanNextTarget(targetId + 1);
            }, 1);
        }
    });
}
function checkXY(s0, xCenter, yCenter)
{
    for (var i = 0; i < g_aTargetList.length; i++)
    {
        if (g_aTargetList[i].lastCounter >= g_nScanCounter) {
            continue;
        }
        var x = g_aTargetList[i].x;
        var y = g_aTargetList[i].y;
        if (!(xCenter - 3 <= x && x <= xCenter + 3 && yCenter - 3 <= y && y <= yCenter + 3)) {
            continue;
        }
        var s1 = ["(", x, ",", y, ")"].join("");
        var s2 = 'da="';
        var s3 = '" title="'var idx1 = s0.indexOf(s1);
        var s = s0.substring(idx1 > 200 ? idx1 - 200 : 0, idx1);
        idx1 = s.lastIndexOf(s2);
        var a = s.substring(idx1 + s2.length, s.indexOf(s3, idx1)).split("`");
        g_aTargetList[i].isRed = a[5] != "0" && a[5] != "--";
        g_aTargetList[i].lastCounter = g_nScanCounter;
    }
}
function markCamp(campName)
{
    for (var i = 0; i < g_aTargetList.length; i++) {
        if (g_aTargetList[i].name == campName) {
            g_aTargetList[i].isRed = false;
        }
    }
    g_sXuatChinh += "`" + campName;
}
var g_nMaxLevel = 100;
function farmNextTarget(aTroop, general)
{
    if (!g_bAutoFarm) {
        return;
    }
    JLog.write(JColor.YELLOW_RED, "aTroop, general<br>", aTroop, general, typeof (aTroop));
    if (typeof (aTroop) != "undefined")
    {
        g_nMaxLevel = 100;
        if (typeof (general) == "undefined") {
            return;
        }
        var total = 0;
        for (var i = 0; i < aTroop.length; i++) {
            total += aTroop[i];
        }
        if (total == 0) {
            return;
        }
        while (g_nMaxLevel > 0)
        {
            var groundAtk = 0;
            var horseAtk = 0;
            for (var i = 0; i < 5; i++)
            {
                groundAtk += aTroop[i] * heso[g_troopType][0][i] * (g_aTroopSkill[i] / 100 + 1);
                horseAtk += aTroop[i] * heso[g_troopType][1][i] * (g_aTroopSkill[i] / 100 + 1);
            }
            groundAtk = Math.round((groundAtk + general.attack / 2) * (general.atkPercent / 100 + 1));
            horseAtk = Math.round((horseAtk + general.attack / 2) * (general.atkPercent / 100 + 1));
            var totalDamage = groundAtk + horseAtk;
            var camp_groundDef = g_campDef[0][Math.round(g_nMaxLevel / 5) - 1];
            var camp_horseDef = g_campDef[1][Math.round(g_nMaxLevel / 5) - 1];
            var totalDefense = Math.round((camp_groundDef * groundAtk + camp_horseDef * horseAtk) / totalDamage);
            var neededDamage = Math.round(totalDefense * g_multiplier);
            if (totalDamage > neededDamage) {
                break;
            }
            g_nMaxLevel -= 5;
        }
    }
    else {
        g_nMaxLevel = 100;
    }
    JLog.write("Camp max<br>", g_nMaxLevel);
    for (var i = 0; i < g_aTargetList.length; i++)
    {
        if (!g_aTargetList[i].isRed) {
            continue;
        }
        if (g_sXuatChinh.include(g_aTargetList[i].name)) {
            g_aTargetList[i].isRed = false;
            continue;
        }
        g_nTargetX = g_aTargetList[i].x;
        g_nTargetY = g_aTargetList[i].y;
        g_campLevel = g_aTargetList[i].level;
        g_campName = g_aTargetList[i].name;
        if (g_campLevel <= g_nMaxLevel)
        {
            JLog.write(JColor.YELLOW_RED, g_campLevel, g_nTargetX, g_nTargetY, i);
            top.frames[3].window.location.href = $$("div.quick_c")[0].select("a")[1].href;
            return;
        }
    }
    JLog.write("rescan2");
    scanTarget();
    return;
}
function auto_LoRen()
{
    g_checkInfo.blacksmith = false;
    JLog.write(JColor.YELLOW_RED, "... đang đọc thông tin lò rèn...");
    new Ajax.Request(top.frames[1].window.document.getElementById("menuInner_vn_VN").href, 
    {
        method : "get",
        onSuccess : function (response)
        {
            var s = response.responseText;
            var idx1 = s.indexOf('title="Lò rèn`');
            if (idx1 ==- 1)
            {
                g_checkInfo.blacksmith = true;
                JLog.write(JColor.YELLOW_RED, "... không có lò rèn...");
                return;
            }
            var idx2 = s.indexOf('?x=', idx1);
            idx1 = s.indexOf('"></a>', idx2);
            new Ajax.Request(s.substring(idx1, idx2), 
            {
                method : "get",
                onSuccess : function (response)
                {
                    var s = response.responseText;
                    var idx1 =- 1;
                    var idx2 =- 1;
                    var s1 = 'class="icond troop_';
                    var s2 = 'class="icon att_a">';
                    var s3 = '%';
                    var a = [];
                    for (var i = 0; i < 7; i++)
                    {
                        idx1 = s.indexOf('id="troopIcon' + i);
                        if (idx1 ==- 1) {
                            break;
                        }
                        idx2 = s.indexOf(s1, idx1);
                        var imageNo = parseInt(s.substr(idx2 + s1.length, 2));
                        var troopType = (imageNo - 1) % 7;
                        g_troopType = imageNo <= 7 ? "nguy" : imageNo <= 14 ? "ngo" : "thuc"idx1 = s.indexOf(s2, 
                        idx2);
                        var atkPercent = parseInt(s.substr(idx1 + s2.length, 2));
                        g_aTroopSkill[troopType] = atkPercent;
                    }
                },
                onFaluire : function (response)
                {
                    JLog.write(JColor.YELLOW_RED, "Lò rèn");
                },
                onComplete : function ()
                {
                    g_checkInfo.blacksmith = true;
                    JLog.write(JColor.YELLOW_RED, "... đã đọc thông tin lò rèn...<br>", g_aTroopSkill);
                    setTimeout(function ()
                    {
                        farmNextTarget();
                    }, 1);
                }
            });
        },
        onFaluire : function (response)
        {
            JLog.write(JColor.YELLOW_RED, "Trong thành");
        }
    });
}
